package com.sys.web.async;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sys.dao.impl.DownLoadImpl;
import com.sys.dao.impl.MsgDaoImpl;
import com.sys.domain.Download;

import net.sf.json.JSONObject;

@WebServlet("/myHomeAsy")
public class MyHomeAsy extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String method = request.getParameter("method");
		if(method.equals("delete")) {
			try {
				deleteRecord(request, response);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}else if (method.equals("postMsg")) {
			try {
				postMsg(request, response);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	private void postMsg(HttpServletRequest request, HttpServletResponse response)
			throws SQLException, IOException {
		String msg = request.getParameter("msg");
		String user = (String) request.getSession().getAttribute("user");
		Boolean b1 = new MsgDaoImpl().insertMsg(user, msg);
		Map<String, Boolean> map = new HashMap<>();
		map.put("isSuc", b1);
		response.getWriter().write(JSONObject.fromObject(map).toString());
	}

	private void deleteRecord(HttpServletRequest request, HttpServletResponse response)
			throws SQLException, IOException {
		String user = (String) request.getSession().getAttribute("user");
		String downTime = request.getParameter("downTime");
		Download download = new Download();
		download.setUserId(user);
		download.setDownTime(downTime);
		Boolean b1 = new DownLoadImpl().deleteDownLoadRecord(download);
		Map<String, Boolean> map = new HashMap<>();
		map.put("isdelete", b1);
		response.getWriter().write(JSONObject.fromObject(map).toString());
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}